<!--
  省市区街道管理页面 - 树状结构版本
-->
<template>
  <div class="region-tree-management">
    <el-card class="main-card">
      <template #header>
        <div class="card-header">
          <h3>户外广告总览配置</h3>
          <div class="buttons">
            <el-button type="primary" @click="handleAddTopLevel">新增省份</el-button>
            <el-button v-if="currentParentId" type="default" @click="goBack">返回上级</el-button>
          </div>
        </div>
      </template>
      
      <div v-if="breadcrumbs.length > 0" class="breadcrumb-container">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item @click="goToRoot">户外广告总览配置</el-breadcrumb-item>
          <el-breadcrumb-item 
            v-for="(item, index) in breadcrumbs" 
            :key="index"
            @click="goToBreadcrumb(index)"
          >
            {{ item.name }}
          </el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      
      <div class="main-content">
        <!-- 左侧树状列表 -->
        <div class="tree-container">
          <el-tree
            v-loading="loading"
            ref="treeRef"
            :data="treeData"
            node-key="id"
            :props="{ 
              label: 'name',
              children: 'children'
            }"
            :expand-on-click-node="false"
            highlight-current
            :default-expanded-keys="defaultExpandedKeys"
            @node-click="handleNodeClick"
            @node-expand="handleNodeExpand"
            @node-collapse="handleNodeCollapse"
          >
            <template #default="{ node, data }">
              <span class="custom-tree-node">
                <span>{{ data.name }} 
                  <el-tag size="small">{{ getLevelText(data.level) }}</el-tag>
                  <el-tag size="small" type="info">{{ data.code }}</el-tag>
                </span>
                <span class="node-actions">
                  <el-button
                    v-if="data.level < 4"
                    type="success"
                    link
                    @click="handleAddChild(data)"
                  >
                    新增
                  </el-button>
                  <el-button
                    type="primary"
                    link
                    @click="handleEdit(data)"
                  >
                    编辑
                  </el-button>
                  <el-button
                    type="danger"
                    link
                    @click="handleDelete(data)"
                  >
                    删除
                  </el-button>
                  <el-button 
                    v-if="data.level === 4" 
                    type="info" 
                    link 
                    @click="showUploadDialog(data)"
                  >
                    上传图片
                  </el-button>
                </span>
              </span>
            </template>
          </el-tree>
          
          <!-- 当前无区域数据的提示 -->
          <div v-if="treeData.length === 0 && !loading" class="empty-tip">
            <el-empty description="暂无区域数据" />
          </div>
        </div>
        
        <!-- 右侧预览区 - 只有点击街道级别才会显示 -->
        <div v-if="selectedNode && selectedNode.level === 4" class="preview-container">
          <el-card class="preview-card">
            <template #header>
              <div class="preview-header">
                <span class="preview-title">{{ selectedNode.name }} 详情</span>
              </div>
            </template>
            
            <div class="preview-content">
              <div class="preview-item">
                <span class="preview-label">广告位位置：</span>
                <span class="preview-value">{{ selectedNode.name }}</span>
              </div>
              <div class="preview-item">
                <span class="preview-label">编号：</span>
                <span class="preview-value">{{ selectedNode.code }}</span>
              </div>
              <div class="preview-item">
                <span class="preview-label">级别：</span>
                <span class="preview-value">街道</span>
              </div>
              <div class="preview-item">
                <span class="preview-label">广告性质：</span>
                <span class="preview-value">{{ selectedNode.adType || '暂无' }}</span>
              </div>
              <div class="preview-item">
                <span class="preview-label">面积(㎡)：</span>
                <span class="preview-value">{{ selectedNode.area || '暂无' }}</span>
              </div>
              <div class="preview-item">
                <span class="preview-label">经度：</span>
                <span class="preview-value">{{ selectedNode.longitude || '暂无' }}</span>
              </div>
              <div class="preview-item">
                <span class="preview-label">纬度：</span>
                <span class="preview-value">{{ selectedNode.latitude || '暂无' }}</span>
              </div>
              
              <!-- 地图点位图预览区 -->
              <div class="image-preview" v-if="selectedNode.imageUrl">
                <h4>地图点位图：</h4>
                <el-image 
                  :src="selectedNode.imageUrl"
                  fit="cover"
                  :preview-src-list="[selectedNode.imageUrl]"
                  preview-teleported
                  :initial-index="0"
                  referrer-policy="no-referrer"
                  crossorigin="anonymous"
                >
                  <template #error>
                    <div class="image-error">
                      <el-icon><icon-picture /></el-icon>
                      <span>图片加载失败，请检查图片链接</span>
                      <el-button size="small" type="primary" @click="openImageInNewTab(selectedNode.imageUrl)">
                        在新窗口打开
                      </el-button>
                    </div>
                  </template>
                  <template #placeholder>
                    <div class="image-loading">
                      <el-icon class="is-loading"><loading /></el-icon>
                      <span>加载中...</span>
                    </div>
                  </template>
                </el-image>
              </div>
              
              <!-- 广告实位图预览区 -->
              <div class="image-preview" v-if="selectedNode.adRealImageUrl">
                <h4>广告实位图：</h4>
                <el-image 
                  :src="selectedNode.adRealImageUrl"
                  fit="cover"
                  :preview-src-list="[selectedNode.adRealImageUrl]"
                  preview-teleported
                  :initial-index="0"
                  referrer-policy="no-referrer"
                  crossorigin="anonymous"
                >
                  <template #error>
                    <div class="image-error">
                      <el-icon><icon-picture /></el-icon>
                      <span>图片加载失败，请检查图片链接</span>
                      <el-button size="small" type="primary" @click="openImageInNewTab(selectedNode.adRealImageUrl)">
                        在新窗口打开
                      </el-button>
                    </div>
                  </template>
                  <template #placeholder>
                    <div class="image-loading">
                      <el-icon class="is-loading"><loading /></el-icon>
                      <span>加载中...</span>
                    </div>
                  </template>
                </el-image>
              </div>
              
              <div class="no-image" v-if="!selectedNode.imageUrl && !selectedNode.adRealImageUrl">
                <el-empty description="暂无图片" :image-size="100">
                  <template #description>
                    <p>暂无地图点位图和广告实位图，请点击"上传图片"按钮上传</p>
                  </template>
                  <el-button type="primary" @click="showUploadDialog(selectedNode)">
                    上传图片
                  </el-button>
                </el-empty>
              </div>
              
              <!-- 经纬度地图标记点 -->
              <div class="map-link" v-if="selectedNode.longitude && selectedNode.latitude">
                <el-link 
                  :href="`https://maps.google.com/?q=${selectedNode.latitude},${selectedNode.longitude}`" 
                  target="_blank" 
                  type="primary"
                >
                  <el-icon><location /></el-icon>
                  在地图中查看位置
                </el-link>
              </div>
            </div>
          </el-card>
        </div>
      </div>
    </el-card>
    
    <!-- 新增/编辑弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑区域' : '新增区域'"
      width="500px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="父级区域">
          <el-select 
            v-model="form.parentId" 
            placeholder="请选择父级区域" 
            clearable 
            style="width: 100%"
            @change="handleParentChange"
          >
            <el-option v-if="form.level === 1" label="无父级（顶级区域）" :value="null" />
            <el-option 
              v-for="region in filteredParents" 
              :key="region.id" 
              :label="getRegionDisplayLabel(region)" 
              :value="region.id" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="广告位位置" prop="name">
          <el-input v-model="form.name" placeholder="请输入广告位位置" />
        </el-form-item>
        <el-form-item label="编号" prop="code">
          <el-input v-model="form.code" placeholder="请输入编号" />
        </el-form-item>
        <el-form-item label="级别" prop="level">
          <el-select 
            v-model="form.level" 
            placeholder="请选择级别" 
            style="width: 100%"
            @change="handleLevelChange"
          >
            <el-option label="省" :value="1" />
            <el-option label="市" :value="2" />
            <el-option label="区/县" :value="3" />
            <el-option label="街道" :value="4" />
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="sortOrder">
          <el-input-number v-model="form.sortOrder" :min="0" style="width: 100%" />
        </el-form-item>
        <!-- 只有街道级别才显示经纬度、广告性质和图片 -->
        <template v-if="form.level === 4">
          <el-form-item label="广告性质" prop="adType">
            <el-input v-model="form.adType" placeholder="请输入广告性质" />
          </el-form-item>
          <el-form-item label="面积(㎡)" prop="area">
            <el-input-number 
              v-model="form.area" 
              :min="0.01" 
              :precision="2" 
              :step="0.01" 
              style="width: 100%" 
              placeholder="请输入面积"
            />
          </el-form-item>
          <el-form-item label="经度" prop="longitude">
            <el-input-number 
              v-model="form.longitude" 
              :precision="6" 
              :step="0.000001" 
              style="width: 100%" 
              placeholder="请输入经度"
            />
          </el-form-item>
          <el-form-item label="纬度" prop="latitude">
            <el-input-number 
              v-model="form.latitude" 
              :precision="6" 
              :step="0.000001" 
              style="width: 100%" 
              placeholder="请输入纬度"
            />
          </el-form-item>
          
          <!-- 地图点位图编辑 -->
          <el-form-item label="地图点位图">
            <div class="street-image-editor">
              <!-- 当前图片显示 -->
              <div v-if="form.imageUrl && !newImagePreview" class="current-image-container">
                <div class="image-wrapper">
                  <el-image 
                    :src="form.imageUrl"
                    class="street-image"
                    fit="cover"
                    :preview-src-list="[form.imageUrl]"
                    preview-teleported
                  >
                    <template #error>
                      <div class="image-error">
                        <el-icon><icon-picture /></el-icon>
                        <span>图片加载失败</span>
                      </div>
                    </template>
                  </el-image>
                  <div class="image-overlay">
                    <el-button size="small" type="danger" circle @click="removeStreetImage">
                      <el-icon><delete /></el-icon>
                    </el-button>
                  </div>
                </div>
                <div class="image-actions">
                  <el-upload
                    :show-file-list="false"
                    :auto-upload="false"
                    :on-change="handleImageUpload"
                    accept="image/*"
                  >
                    <el-button type="primary" size="small">
                      <el-icon><UploadFilled /></el-icon>
                      更换图片
                    </el-button>
                  </el-upload>
                </div>
              </div>
              
              <!-- 新图片预览 -->
              <div v-else-if="newImagePreview" class="new-image-container">
                <div class="image-wrapper">
                  <el-image 
                    :src="newImagePreview" 
                    class="street-image"
                    fit="cover"
                  />
                  <div class="image-overlay">
                    <el-button size="small" circle @click="cancelImageUpload">
                      <el-icon><close /></el-icon>
                    </el-button>
                  </div>
                </div>
                <div class="image-actions">
                  <el-button type="success" size="small" @click="confirmImageUpload">
                    <el-icon><check /></el-icon>
                    确认上传
                  </el-button>
                  <el-button size="small" @click="cancelImageUpload">
                    取消
                  </el-button>
                </div>
              </div>
              
              <!-- 上传区域 -->
              <div v-else class="upload-area">
                <el-upload
                  class="image-uploader"
                  :show-file-list="false"
                  :auto-upload="false"
                  :on-change="handleImageUpload"
                  accept="image/*"
                  drag
                >
                  <div class="upload-content">
                    <el-icon class="upload-icon"><UploadFilled /></el-icon>
                    <div class="upload-text">
                      <div>点击或拖拽上传地图点位图</div>
                      <div class="upload-hint">支持 JPG/PNG 格式，大小不超过 10MB</div>
                    </div>
                  </div>
                </el-upload>
              </div>
            </div>
          </el-form-item>

          <!-- 广告实位图编辑 -->
          <el-form-item label="广告实位图">
            <div class="street-image-editor">
              <!-- 当前广告实位图显示 -->
              <div v-if="form.adRealImageUrl && !newAdRealImagePreview" class="current-image-container">
                <div class="image-wrapper">
                  <el-image 
                    :src="form.adRealImageUrl"
                    class="street-image"
                    fit="cover"
                    :preview-src-list="[form.adRealImageUrl]"
                    preview-teleported
                  >
                    <template #error>
                      <div class="image-error">
                        <el-icon><icon-picture /></el-icon>
                        <span>图片加载失败</span>
                      </div>
                    </template>
                  </el-image>
                  <div class="image-overlay">
                    <el-button size="small" type="danger" circle @click="removeAdRealImage">
                      <el-icon><delete /></el-icon>
                    </el-button>
                  </div>
                </div>
                <div class="image-actions">
                  <el-upload
                    :show-file-list="false"
                    :auto-upload="false"
                    :on-change="handleAdRealImageUpload"
                    accept="image/*"
                  >
                    <el-button type="primary" size="small">
                      <el-icon><UploadFilled /></el-icon>
                      更换图片
                    </el-button>
                  </el-upload>
                </div>
              </div>
              
              <!-- 新广告实位图预览 -->
              <div v-else-if="newAdRealImagePreview" class="new-image-container">
                <div class="image-wrapper">
                  <el-image 
                    :src="newAdRealImagePreview" 
                    class="street-image"
                    fit="cover"
                  />
                  <div class="image-overlay">
                    <el-button size="small" circle @click="cancelAdRealImageUpload">
                      <el-icon><close /></el-icon>
                    </el-button>
                  </div>
                </div>
                <div class="image-actions">
                  <el-button type="success" size="small" @click="confirmAdRealImageUpload">
                    <el-icon><check /></el-icon>
                    确认上传
                  </el-button>
                  <el-button size="small" @click="cancelAdRealImageUpload">
                    取消
                  </el-button>
                </div>
              </div>
              
              <!-- 广告实位图上传区域 -->
              <div v-else class="upload-area">
                <el-upload
                  class="image-uploader"
                  :show-file-list="false"
                  :auto-upload="false"
                  :on-change="handleAdRealImageUpload"
                  accept="image/*"
                  drag
                >
                  <div class="upload-content">
                    <el-icon class="upload-icon"><UploadFilled /></el-icon>
                    <div class="upload-text">
                      <div>点击或拖拽上传广告实位图</div>
                      <div class="upload-hint">支持 JPG/PNG 格式，大小不超过 10MB</div>
                    </div>
                  </div>
                </el-upload>
              </div>
            </div>
          </el-form-item>
        </template>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 上传图片弹窗 -->
    <el-dialog
      v-model="uploadDialogVisible"
      title="上传街道图片"
      width="500px"
    >
      <div v-if="selectedRegion && selectedRegion.imageUrl" class="current-image">
        <h4>当前图片：</h4>
        <el-image 
          :src="selectedRegion.imageUrl"
          style="max-width: 100%; max-height: 200px"
        />
      </div>
      
      <el-upload
        class="upload-demo"
        drag
        action="#"
        :auto-upload="false"
        :limit="1"
        :on-change="handleFileChange"
        :file-list="fileList"
        :show-file-list="false"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          拖拽文件到此处，或 <em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            请上传JPG/PNG格式图片，大小不超过10MB
          </div>
        </template>
      </el-upload>
      
      <!-- 添加图片预览区域 -->
      <div v-if="imagePreview" class="upload-preview">
        <h4>图片预览：</h4>
        <div class="preview-image-container">
          <el-image 
            :src="imagePreview" 
            style="max-width: 100%; max-height: 200px" 
            fit="contain"
          />
          <div class="preview-info">
            <span>{{ uploadFileName }}</span>
            <el-button type="danger" size="small" @click="cancelPreview" circle>
              <el-icon><delete /></el-icon>
            </el-button>
          </div>
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelUpload">取消</el-button>
          <el-button type="primary" @click="submitUpload" :disabled="!uploadFile">上传</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, nextTick, watch } from 'vue'
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus'
import { UploadFilled, Picture as IconPicture, Location, Delete, Loading, Check, Close } from '@element-plus/icons-vue'
import axios from '../../utils/axios'
import { useRouter } from 'vue-router'

const router = useRouter()

// 树形数据
const treeData = ref([])
const loading = ref(false)
const currentParentId = ref(null)
const breadcrumbs = ref([])
const treeRef = ref(null)
const defaultExpandedKeys = ref([]) // 默认展开的节点
const expandedKeys = ref([]) // 当前展开的节点，用于保持状态

// 选中的节点（用于右侧预览）
const selectedNode = ref(null)

// 选中的区域（用于上传图片等操作）
const selectedRegion = ref(null)

// 可用的父级区域列表
const availableParents = ref([])

// 过滤后的父级区域列表（根据级别筛选）
const filteredParents = ref([])

// 是否显示经纬度字段（只对街道级别显示）
const showGeoFields = computed(() => {
  if (!treeData.value || treeData.value.length === 0) return false
  return treeData.value.some(item => item.level === 4)
})

// 新增/编辑弹窗相关
const dialogVisible = ref(false)
const isEdit = ref(false)
const formRef = ref<FormInstance>()
const form = reactive({
  id: null,
  parentId: null,
  parentName: '',
  name: '',
  code: '',
  level: 1,
  sortOrder: 0,
  longitude: null,
  latitude: null,
  imageUrl: '',
  adType: '',
  adRealImageUrl: '',
  area: 0.00,
})

// 重置表单
const resetForm = () => {
  form.id = null
  form.parentId = null
  form.parentName = ''
  form.name = ''
  form.code = ''
  form.level = 1
  form.sortOrder = 0
  form.longitude = null
  form.latitude = null
  form.imageUrl = ''
  form.adType = ''
  form.adRealImageUrl = ''
  form.area = 0.00
  
  // 重置过滤后的父级区域列表
  filteredParents.value = []
  
  // 清理图片上传相关数据
  newImagePreview.value = ''
  newUploadFile.value = null
  newUploadFileName.value = ''
  newAdRealImagePreview.value = ''
  newAdRealUploadFile.value = null
  newAdRealUploadFileName.value = ''
}

// 加载可用的父级区域
const loadAvailableParents = async (excludeId = null) => {
  try {
    // 使用all接口获取所有区域的扁平化列表
    const response = await axios.get('/api/regions/all')
    let regions = response.data || []
    
    // 如果是编辑模式，排除当前区域及其子区域
    if (excludeId) {
      regions = regions.filter(region => {
        return region.id !== excludeId && !isDescendantOf(region.id, excludeId, regions)
      })
    }
    
    // 按级别和名称排序，便于选择
    regions.sort((a, b) => {
      if (a.level !== b.level) {
        return a.level - b.level
      }
      return a.name.localeCompare(b.name)
    })
    
    availableParents.value = regions
    
    // 根据当前表单的级别进行筛选
    filterParentsByLevel(form.level)
  } catch (error) {
    console.error('加载可用父级区域失败', error)
    availableParents.value = []
    filteredParents.value = []
  }
}

// 检查是否为子孙节点
const isDescendantOf = (childId, ancestorId, allRegions) => {
  const child = allRegions.find(r => r.id === childId)
  if (!child || !child.parentId) return false
  
  if (child.parentId === ancestorId) return true
  
  return isDescendantOf(child.parentId, ancestorId, allRegions)
}

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入广告位位置', trigger: 'blur' },
    { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入编号', trigger: 'blur' },
    { pattern: /^\d{2,20}$/, message: '编号必须为2-20位数字', trigger: 'blur' }
  ],
  sortOrder: [
    { required: true, message: '请输入排序号', trigger: 'blur' }
  ],
}

// 上传图片相关
const uploadDialogVisible = ref(false)
const fileList = ref([])
const uploadFile = ref(null)
const imagePreview = ref('') // 图片预览URL
const uploadFileName = ref('') // 上传文件名

// 街道图片编辑相关
const newImagePreview = ref('')
const newUploadFile = ref(null)
const newUploadFileName = ref('')

// 广告实位图编辑相关
const newAdRealImagePreview = ref('')
const newAdRealUploadFile = ref(null)
const newAdRealUploadFileName = ref('')

// 保存当前展开状态
const saveExpandedState = () => {
  if (treeRef.value) {
    try {
      // 方法1：直接获取展开的节点keys
      const keys = treeRef.value.getExpandedKeys?.() || []
      expandedKeys.value = [...keys]
      console.log('保存展开状态:', expandedKeys.value)
      return expandedKeys.value
    } catch (error) {
      console.error('保存展开状态失败:', error)
      return []
    }
  }
  return []
}

// 恢复展开状态
const restoreExpandedState = async (savedKeys = null) => {
  const keysToRestore = savedKeys || expandedKeys.value
  if (keysToRestore && keysToRestore.length > 0) {
    console.log('准备恢复展开状态:', keysToRestore)
    
    // 等待DOM更新完成
    await nextTick()
    
    // 多次尝试设置展开状态
    let attempts = 0
    const maxAttempts = 5
    
    const tryRestore = async () => {
      attempts++
      console.log(`第${attempts}次尝试恢复展开状态`)
      
      if (treeRef.value) {
        try {
          // 更新defaultExpandedKeys
          defaultExpandedKeys.value = [...keysToRestore]
          
          // 尝试使用setExpandedKeys方法
          if (treeRef.value.setExpandedKeys) {
            treeRef.value.setExpandedKeys(keysToRestore)
            console.log('使用setExpandedKeys方法成功')
            return true
          }
        } catch (error) {
          console.warn(`第${attempts}次尝试失败:`, error)
        }
      }
      
      if (attempts < maxAttempts) {
        setTimeout(tryRestore, 100 * attempts) // 递增延迟
      } else {
        console.log('所有恢复尝试都失败了，只能依靠defaultExpandedKeys')
      }
      
      return false
    }
    
    tryRestore()
  }
}

// 初始化
onMounted(() => {
  loadRegionTree()
  
  // 初始化时监听树组件的变化
  setTimeout(() => {
    if (treeRef.value) {
      console.log('树组件已加载')
    }
  }, 500)
})

// 监听treeData变化，确保在数据更新后能正确设置展开状态
watch(() => treeData.value, (newData) => {
  if (newData && newData.length > 0 && expandedKeys.value.length > 0) {
    console.log('treeData已更新，准备恢复展开状态')
    nextTick(() => {
      restoreExpandedState()
    })
  }
}, { flush: 'post' })

// 加载区域树
const loadRegionTree = async (preserveExpandedState = false) => {
  loading.value = true
  try {
    const response = await axios.get('/api/regions/tree')
    treeData.value = (response.data || []).map(item => processTreeNode(item))
    
    if (!preserveExpandedState) {
      // 初始加载时，设置默认展开的节点（只展开第一级节点）
      defaultExpandedKeys.value = treeData.value.map(node => node.id)
      expandedKeys.value = [...defaultExpandedKeys.value]
    } else {
      // 保持之前的展开状态
      defaultExpandedKeys.value = [...expandedKeys.value]
    }
    
    currentParentId.value = null
    breadcrumbs.value = []
  } catch (error) {
    console.error('加载区域树失败', error)
    ElMessage.error('加载区域树失败')
    treeData.value = []
  } finally {
    loading.value = false
  }
}

// 处理树节点数据
const processTreeNode = (node) => {
  // 处理数字和布尔值类型
  const processedNode = {
    ...node,
    level: Number(node.level || 1),
    sortOrder: Number(node.sortOrder || 0),
    hasChildren: Boolean(node.hasChildren),
    isStreet: Boolean(node.isStreet)
  }
  
  // 如果有子节点，递归处理
  if (node.children && node.children.length > 0) {
    processedNode.children = node.children.map(child => processTreeNode(child))
  }
  
  return processedNode
}

// 加载面包屑导航数据
const loadBreadcrumbs = async (id) => {
  try {
    const response = await axios.get(`/api/regions/${id}/path`)
    breadcrumbs.value = (response.data || []).map(item => ({
      id: item.id,
      name: item.name,
      level: Number(item.level || 1)
    }))
  } catch (error) {
    console.error('加载面包屑导航失败', error)
    breadcrumbs.value = []
  }
}

// 返回根级
const goToRoot = () => {
  loadRegionTree()
}

// 通过面包屑导航
const goToBreadcrumb = (index) => {
  if (index >= 0 && index < breadcrumbs.value.length) {
    const id = breadcrumbs.value[index].id
    loadTreeForParent(id)
  }
}

// 加载指定父节点的树
const loadTreeForParent = async (parentId, preserveExpandedState = false) => {
  loading.value = true
  try {
    const response = await axios.get('/api/regions/tree', {
      params: { parentId }
    })
    treeData.value = (response.data || []).map(item => processTreeNode(item))
    
    // 设置默认展开的节点（只展开当前加载的节点）
    defaultExpandedKeys.value = treeData.value.map(node => node.id)
    
    currentParentId.value = parentId
    
    // 加载面包屑
    if (parentId) {
      await loadBreadcrumbs(parentId)
    } else {
      breadcrumbs.value = []
    }
    
    if (!preserveExpandedState) {
      // 初始加载时，设置默认展开的节点（只展开第一级节点）
      defaultExpandedKeys.value = treeData.value.map(node => node.id)
      expandedKeys.value = [...defaultExpandedKeys.value]
    } else {
      // 保持之前的展开状态
      defaultExpandedKeys.value = [...expandedKeys.value]
    }
  } catch (error) {
    console.error('加载区域树失败', error)
    ElMessage.error('加载区域树失败')
    treeData.value = []
  } finally {
    loading.value = false
  }
}

// 返回上级
const goBack = () => {
  if (breadcrumbs.value.length > 0) {
    // 如果只有一级面包屑，则返回根级
    if (breadcrumbs.value.length === 1) {
      goToRoot()
    } else {
      // 否则返回到上一级面包屑指向的区域
      const parentIndex = breadcrumbs.value.length - 2
      if (parentIndex >= 0) {
        loadTreeForParent(breadcrumbs.value[parentIndex].id)
      }
    }
  } else {
    goToRoot()
  }
}

// 新增顶级区域
const handleAddTopLevel = async () => {
  isEdit.value = false
  resetForm()
  form.level = 1
  
  // 加载可用父级区域
  await loadAvailableParents()
  
  dialogVisible.value = true
  
  // 清除表单验证
  setTimeout(() => {
    formRef.value?.clearValidate()
  }, 0)
}

// 新增子区域
const handleAddChild = async (data) => {
  if (data.level >= 4) {
    ElMessage.warning('街道级别不能再添加子区域')
    return
  }
  
  isEdit.value = false
  resetForm()
  form.parentId = data.id
  form.level = data.level + 1
  
  // 加载可用父级区域
  await loadAvailableParents()
  
  dialogVisible.value = true
  
  // 清除表单验证
  setTimeout(() => {
    formRef.value?.clearValidate()
  }, 0)
}

// 编辑区域
const handleEdit = async (data) => {
  isEdit.value = true
  resetForm()
  
  // 复制数据到表单
  form.id = data.id
  form.parentId = data.parentId
  form.name = data.name
  form.code = data.code
  form.level = Number(data.level || 1)
  form.sortOrder = Number(data.sortOrder || 0)
  
  if (data.level === 4) {
    form.longitude = data.longitude !== null && data.longitude !== undefined ? Number(data.longitude) : null
    form.latitude = data.latitude !== null && data.latitude !== undefined ? Number(data.latitude) : null
    form.imageUrl = data.imageUrl || ''
    form.adType = data.adType || ''
    form.adRealImageUrl = data.adRealImageUrl || ''
    form.area = data.area || 0.00
  }
  
  // 加载可用父级区域（排除当前区域及其子区域）
  await loadAvailableParents(data.id)
  
  dialogVisible.value = true
  
  // 清除表单验证
  setTimeout(() => {
    formRef.value?.clearValidate()
  }, 0)
}

// 删除区域
const handleDelete = (data) => {
  ElMessageBox.confirm('确定要删除该区域吗？如果有子区域将无法删除。', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await axios.delete(`/api/regions/${data.id}`)
      ElMessage.success('删除成功')
      
      // 刷新树状数据并保持展开状态
      if (currentParentId.value) {
        await loadTreeForParent(currentParentId.value, true)
      } else {
        await loadRegionTree(true)
      }
      
      // watch会自动恢复展开状态，无需手动调用
    } catch (error) {
      if (error.response && error.response.data && error.response.data.message) {
        ElMessage.error(error.response.data.message)
      } else {
        ElMessage.error('删除失败，可能该区域下有子区域')
      }
    }
  }).catch(() => {
    // 取消删除
  })
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 处理表单数据
        const regionData = {
          id: form.id,
          parentId: form.parentId,
          name: form.name,
          code: form.code,
          level: Number(form.level),
          sortOrder: Number(form.sortOrder || 0),
          longitude: null,
          latitude: null,
          adType: form.adType,
          adRealImageUrl: form.adRealImageUrl,
          area: Number(form.area || 0.00),
        }
        
        // 只有街道级别才设置经纬度
        if (form.level === 4) {
          regionData.longitude = form.longitude !== null && form.longitude !== undefined 
            ? Number(form.longitude) : null
          regionData.latitude = form.latitude !== null && form.latitude !== undefined 
            ? Number(form.latitude) : null
        }
        
        // 保存区域
        const savedRegion = await axios.post('/api/regions', regionData)
        
        // 如果是新增的街道且有待上传的图片
        if (!form.id && form.level === 4 && newUploadFile.value && savedRegion.data.id) {
          try {
            const formData = new FormData()
            formData.append('file', newUploadFile.value)
            
            const imageResponse = await axios.post(`/api/regions/${savedRegion.data.id}/image`, formData, {
              headers: {
                'Content-Type': 'multipart/form-data'
              }
            })
            
            ElMessage.success(isEdit.value ? '更新成功，图片已上传' : '新增成功，图片已上传')
          } catch (imageError) {
            console.error('图片上传失败', imageError)
            ElMessage.warning(isEdit.value ? '更新成功，但图片上传失败' : '新增成功，但图片上传失败')
          }
        } else {
          ElMessage.success(isEdit.value ? '更新成功' : '新增成功')
        }
        
        dialogVisible.value = false
        
        // 刷新树状数据并保持展开状态
        if (currentParentId.value) {
          await loadTreeForParent(currentParentId.value, true)
        } else {
          await loadRegionTree(true)
        }
        
        // watch会自动恢复展开状态，无需手动调用
      } catch (error) {
        console.error('保存失败', error)
        if (error.response && error.response.data && error.response.data.message) {
          ElMessage.error(error.response.data.message)
        } else {
          ElMessage.error('保存失败')
        }
      }
    }
  })
}

// 显示上传对话框
const showUploadDialog = (row) => {
  if (!row || row.level !== 4) {
    ElMessage.warning('只有街道级别才能上传图片')
    return
  }
  
  selectedRegion.value = row
  fileList.value = []
  uploadFile.value = null
  uploadDialogVisible.value = true
}

// 处理文件变更
const handleFileChange = (file) => {
  uploadFile.value = file.raw
  uploadFileName.value = file.name
  
  // 验证文件类型
  const isImage = file.raw.type.startsWith('image/')
  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    fileList.value = []
    uploadFile.value = null
    imagePreview.value = ''
    return
  }
  
  // 验证文件大小
  const isLt10M = file.size / 1024 / 1024 < 10
  if (!isLt10M) {
    ElMessage.error('图片大小不能超过 10MB!')
    fileList.value = []
    uploadFile.value = null
    imagePreview.value = ''
    return
  }
  
  // 生成预览URL
  imagePreview.value = URL.createObjectURL(file.raw)
}

// 取消预览
const cancelPreview = () => {
  if (imagePreview.value) {
    URL.revokeObjectURL(imagePreview.value)
  }
  imagePreview.value = ''
  uploadFile.value = null
  uploadFileName.value = ''
  fileList.value = []
}

// 取消上传
const cancelUpload = () => {
  uploadDialogVisible.value = false
  cancelPreview()
  selectedRegion.value = null
}

// 提交上传
const submitUpload = async () => {
  if (!uploadFile.value) {
    ElMessage.warning('请先选择要上传的图片')
    return
  }
  
  if (!selectedRegion.value || !selectedRegion.value.id) {
    ElMessage.warning('请先选择一个街道')
    uploadDialogVisible.value = false
    return
  }
  
  try {
    const formData = new FormData()
    formData.append('file', uploadFile.value)
    
    const response = await axios.post(
      `/api/regions/${selectedRegion.value.id}/image`,
      formData,
      {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }
    )
    
    ElMessage.success('上传成功')
    uploadDialogVisible.value = false
    
    // 如果当前选中的预览节点就是上传的节点，同步更新图片URL
    if (selectedNode.value && selectedNode.value.id === selectedRegion.value.id) {
      selectedNode.value.imageUrl = response.data
    }
    
    // 刷新树状数据并保持展开状态
    if (currentParentId.value) {
      await loadTreeForParent(currentParentId.value, true)
    } else {
      await loadRegionTree(true)
    }
    
    // watch会自动恢复展开状态，无需手动调用
  } catch (error) {
    console.error('上传失败', error)
    if (error.response && error.response.data && error.response.data.message) {
      ElMessage.error(error.response.data.message)
    } else {
      ElMessage.error('上传失败')
    }
  }
}

// 获取级别文本
const getLevelText = (level) => {
  // 确保level是数字类型
  const numLevel = parseInt(level, 10)
  
  // 如果转换后不是有效数字，返回未知
  if (isNaN(numLevel)) {
    return '未知'
  }
  
  switch (numLevel) {
    case 1: return '省'
    case 2: return '市'
    case 3: return '区/县'
    case 4: return '街道'
    default: return '未知'
  }
}

// 处理节点点击事件
const handleNodeClick = (data) => {
  // 只有点击街道级别才设置选中的节点，用于右侧预览
  if (data.level === 4) {
    selectedNode.value = { ...data }
  } else {
    selectedNode.value = null
  }
}

const openImageInNewTab = (url) => {
  if (url) {
    window.open(url, '_blank');
  }
}

// 处理父级选择变更
const handleParentChange = async (parentId) => {
  // 父级选择变更时不再自动修改级别
  // 级别选择是主导的，父级选择只是在对应级别范围内选择
  if (parentId) {
    try {
      // 验证选择的父级级别是否正确
      const response = await axios.get(`/api/regions/${parentId}`)
      const parent = response.data
      const expectedParentLevel = form.level - 1
      
      if (parent.level !== expectedParentLevel) {
        ElMessage.warning(`选择的父级区域级别不匹配，应选择${getLevelText(expectedParentLevel)}级别的区域`)
        form.parentId = null
      }
    } catch (error) {
      console.error('获取父级区域信息失败', error)
    }
  }
}

// 处理级别选择变更
const handleLevelChange = async (level) => {
  // 如果availableParents还没有加载，等待一下
  if (availableParents.value.length === 0) {
    console.log('availableParents为空，等待加载...')
    // 等待最多1秒，看看数据是否会加载
    for (let i = 0; i < 10; i++) {
      await new Promise(resolve => setTimeout(resolve, 100))
      if (availableParents.value.length > 0) {
        console.log('availableParents已加载，数量:', availableParents.value.length)
        break
      }
    }
  }
  
  // 先根据级别过滤父级区域选项
  filterParentsByLevel(level)
  
  if (level === 1) {
    // 省级区域没有父级
    form.parentId = null
  } else {
    // 检查当前选择的父级是否还在新的筛选结果中
    if (form.parentId) {
      const currentParent = availableParents.value.find(region => region.id === form.parentId)
      if (currentParent && currentParent.level === level - 1) {
        // 当前父级级别正确，保持选择
        return
      }
    }
    
    // 如果当前父级不合适，尝试智能选择
    const suitableParents = filteredParents.value
    
    if (isEdit.value && form.id) {
      // 编辑模式：根据当前区域的层级关系来智能选择父级
      const selectedParent = await findAppropriateParent(level, suitableParents)
      if (selectedParent) {
        form.parentId = selectedParent.id
        console.log('智能选择父级:', selectedParent.name)
        return
      }
    }
    
    if (suitableParents.length === 1) {
      // 如果只有一个合适的父级，自动选择它
      form.parentId = suitableParents[0].id
    } else if (suitableParents.length > 1) {
      // 如果有多个选择，不自动选择，让用户手动选择
      form.parentId = null
    } else {
      // 没有合适的父级
      form.parentId = null
    }
  }
}

// 在编辑模式下智能选择合适的父级区域
const findAppropriateParent = async (targetLevel, suitableParents) => {
  if (!form.id || !suitableParents.length) {
    return null
  }
  
  try {
    // 获取当前区域的完整路径
    const pathResponse = await axios.get(`/api/regions/${form.id}/path`)
    const currentPath = pathResponse.data || []
    
    console.log('当前区域路径:', currentPath.map(p => `${p.name}(${p.level})`))
    
    // 在路径中找到目标级别的父级
    if (targetLevel > 1) {
      const parentLevel = targetLevel - 1
      const parentInPath = currentPath.find(p => p.level === parentLevel)
      
      if (parentInPath) {
        // 在可选父级中找到对应的区域
        const matchedParent = suitableParents.find(p => p.id === parentInPath.id)
        if (matchedParent) {
          console.log('在路径中找到合适的父级:', matchedParent.name)
          return matchedParent
        }
      }
    }
    
    return null
  } catch (error) {
    console.error('获取区域路径失败:', error)
    return null
  }
}

// 根据级别过滤父级区域选项
const filterParentsByLevel = (level) => {
  if (level === 1) {
    // 省级区域没有父级，清空选项
    filteredParents.value = []
  } else {
    // 获取对应的父级级别
    const parentLevel = level - 1
    
    // 从所有可用父级中筛选出对应级别的区域
    if (availableParents.value.length > 0) {
      filteredParents.value = availableParents.value.filter(region => region.level === parentLevel)
    } else {
      // 如果还没有加载可用父级区域，先清空筛选结果
      filteredParents.value = []
    }
  }
}

// 获取区域显示标签
const getRegionDisplayLabel = (region) => {
  const levelText = getLevelText(region.level)
  return `${levelText} - ${region.name} (${region.code})`
}

const handleImageUpload = (file) => {
  newUploadFile.value = file.raw
  newUploadFileName.value = file.name
  
  // 验证文件类型
  const isImage = file.raw.type.startsWith('image/')
  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    newUploadFile.value = null
    newImagePreview.value = ''
    return
  }
  
  // 验证文件大小
  const isLt10M = file.size / 1024 / 1024 < 10
  if (!isLt10M) {
    ElMessage.error('图片大小不能超过 10MB!')
    newUploadFile.value = null
    newImagePreview.value = ''
    return
  }
  
  // 生成预览URL
  newImagePreview.value = URL.createObjectURL(file.raw)
}

const confirmImageUpload = async () => {
  if (!newUploadFile.value) {
    ElMessage.warning('请先选择图片')
    return
  }
  
  if (!form.id) {
    // 新增模式，暂存图片等保存区域后再上传
    ElMessage.info('图片将在保存区域时一并上传')
    // 保持预览状态，不清理数据
    return
  }
  
  try {
    const formData = new FormData()
    formData.append('file', newUploadFile.value)
    
    const response = await axios.post(`/api/regions/${form.id}/image`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    
    // 更新表单中的图片URL
    form.imageUrl = response.data
    ElMessage.success('图片上传成功')
    
    // 清理临时数据
    newUploadFile.value = null
    newImagePreview.value = ''
    
  } catch (error) {
    console.error('图片上传失败', error)
    ElMessage.error('图片上传失败')
  }
}

const cancelImageUpload = () => {
  newUploadFile.value = null
  newImagePreview.value = ''
}

const removeStreetImage = async () => {
  if (!form.imageUrl) {
    return
  }
  
  try {
    await ElMessageBox.confirm('确定要删除这张图片吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    if (form.id) {
      // 编辑模式，删除服务器上的图片
      try {
        await axios.delete(`/api/regions/${form.id}/image`)
        ElMessage.success('图片删除成功')
      } catch (error) {
        console.error('删除图片失败', error)
        ElMessage.error('删除图片失败')
        return
      }
    }
    
    // 清空表单中的图片URL
    form.imageUrl = ''
    // 清理预览数据
    newImagePreview.value = ''
    newUploadFile.value = null
    
  } catch {
    // 用户取消删除
  }
}

// 处理节点展开事件
const handleNodeExpand = (nodeData, node, instance) => {
  if (!expandedKeys.value.includes(nodeData.id)) {
    expandedKeys.value.push(nodeData.id)
  }
  console.log('节点展开:', nodeData.name, '当前展开的节点:', expandedKeys.value)
}

// 处理节点折叠事件
const handleNodeCollapse = (nodeData, node, instance) => {
  const index = expandedKeys.value.indexOf(nodeData.id)
  if (index > -1) {
    expandedKeys.value.splice(index, 1)
  }
  console.log('节点折叠:', nodeData.name, '当前展开的节点:', expandedKeys.value)
}

const handleAdRealImageUpload = (file) => {
  newAdRealUploadFile.value = file.raw
  newAdRealUploadFileName.value = file.name
  
  // 验证文件类型
  const isImage = file.raw.type.startsWith('image/')
  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    newAdRealUploadFile.value = null
    newAdRealImagePreview.value = ''
    return
  }
  
  // 验证文件大小
  const isLt10M = file.size / 1024 / 1024 < 10
  if (!isLt10M) {
    ElMessage.error('图片大小不能超过 10MB!')
    newAdRealUploadFile.value = null
    newAdRealImagePreview.value = ''
    return
  }
  
  // 生成预览URL
  newAdRealImagePreview.value = URL.createObjectURL(file.raw)
}

const confirmAdRealImageUpload = async () => {
  if (!newAdRealUploadFile.value) {
    ElMessage.warning('请先选择图片')
    return
  }
  
  if (!form.id) {
    // 新增模式，暂存图片等保存区域后再上传
    ElMessage.info('图片将在保存区域时一并上传')
    // 保持预览状态，不清理数据
    return
  }
  
  try {
    const formData = new FormData()
    formData.append('file', newAdRealUploadFile.value)
    
    const response = await axios.post(`/api/regions/${form.id}/ad-real-image`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    
    // 更新表单中的图片URL
    form.adRealImageUrl = response.data
    ElMessage.success('图片上传成功')
    
    // 清理临时数据
    newAdRealUploadFile.value = null
    newAdRealImagePreview.value = ''
    
  } catch (error) {
    console.error('图片上传失败', error)
    ElMessage.error('图片上传失败')
  }
}

const cancelAdRealImageUpload = () => {
  newAdRealUploadFile.value = null
  newAdRealImagePreview.value = ''
}

const removeAdRealImage = async () => {
  if (!form.adRealImageUrl) {
    return
  }
  
  try {
    await ElMessageBox.confirm('确定要删除这张图片吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    if (form.id) {
      // 编辑模式，删除服务器上的图片
      try {
        await axios.delete(`/api/regions/${form.id}/ad-real-image`)
        ElMessage.success('图片删除成功')
      } catch (error) {
        console.error('删除图片失败', error)
        ElMessage.error('删除图片失败')
        return
      }
    }
    
    // 清空表单中的图片URL
    form.adRealImageUrl = ''
    // 清理预览数据
    newAdRealImagePreview.value = ''
    newAdRealUploadFile.value = null
    
  } catch {
    // 用户取消删除
  }
}
</script>

<style scoped>
.region-tree-management {
  height: 100%;
}

.main-card {
  height: calc(100vh - 140px);
  display: flex;
  flex-direction: column;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
}

.breadcrumb-container {
  margin-top: 10px;
  margin-bottom: 10px;
}

.main-content {
  display: flex;
  flex: 1;
  overflow: hidden;
}

.tree-container {
  flex: 1;
  overflow: auto;
  border-right: 1px solid #ebeef5;
  padding-right: 10px;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
  width: 100%;
}

.node-actions {
  margin-left: 20px;
}

.empty-tip {
  margin-top: 50px;
  text-align: center;
}

.el-breadcrumb-item {
  cursor: pointer;
}

.current-image {
  margin-bottom: 20px;
  border: 1px solid #ebeef5;
  padding: 10px;
  border-radius: 4px;
}

.el-tag {
  margin-left: 5px;
}

.preview-container {
  width: 300px;
  overflow: auto;
  padding-left: 10px;
}

.preview-card {
  height: 100%;
}

.preview-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.preview-title {
  font-weight: bold;
  font-size: 16px;
}

.preview-content {
  padding: 10px 0;
}

.preview-item {
  margin-bottom: 10px;
  display: flex;
}

.preview-label {
  font-weight: bold;
  width: 60px;
  color: #606266;
}

.preview-value {
  flex: 1;
  word-break: break-all;
}

.image-preview {
  margin-top: 20px;
}

.image-preview h4 {
  margin-bottom: 10px;
  color: #606266;
}

.el-image {
  width: 100%;
  max-height: 200px;
  border-radius: 4px;
  border: 1px solid #ebeef5;
}

.image-error {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 150px;
  color: #909399;
}

.no-image {
  margin-top: 20px;
}

.map-link {
  margin-top: 20px;
  text-align: center;
}

.upload-preview {
  margin-top: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 10px;
}

.upload-preview h4 {
  margin-bottom: 10px;
  color: #606266;
}

.preview-image-container {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.preview-info {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  margin-top: 10px;
  padding: 0 10px;
}

.image-info {
  display: none; /* 隐藏图片信息 */
}

.image-url {
  display: none; /* 隐藏图片URL */
}

.image-loading {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 150px;
  color: #909399;
}

.image-loading .el-icon {
  font-size: 24px;
  margin-bottom: 8px;
}

.street-image-editor {
  display: flex;
  flex-direction: column;
  gap: 15px;
  width: 100%;
}

.current-image-container,
.new-image-container {
  border-radius: 12px;
  overflow: hidden;
  background: #ffffff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.image-wrapper {
  position: relative;
  width: 100%;
  height: 200px;
  overflow: hidden;
  border-radius: 8px;
}

.street-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.image-overlay {
  position: absolute;
  top: 8px;
  right: 8px;
  background-color: rgba(0, 0, 0, 0.6);
  border-radius: 50%;
  padding: 4px;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.image-wrapper:hover .image-overlay {
  opacity: 1;
}

.image-actions {
  display: flex;
  justify-content: center;
  gap: 10px;
  margin-top: 12px;
  padding: 12px;
}

.upload-area {
  border: 2px dashed #dcdfe6;
  border-radius: 12px;
  background-color: #fafafa;
  transition: all 0.3s ease;
  overflow: hidden;
}

.upload-area:hover {
  border-color: #409eff;
  background-color: #f0f8ff;
}

.image-uploader {
  width: 100%;
}

.upload-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 20px;
  color: #606266;
}

.upload-icon {
  font-size: 48px;
  color: #c0c4cc;
  margin-bottom: 16px;
  transition: color 0.3s ease;
}

.upload-area:hover .upload-icon {
  color: #409eff;
}

.upload-text {
  text-align: center;
  line-height: 1.6;
}

.upload-text > div:first-child {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 8px;
}

.upload-hint {
  font-size: 12px;
  color: #909399;
}

.image-error {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #c0c4cc;
  background-color: #f5f7fa;
}

.image-error .el-icon {
  font-size: 32px;
  margin-bottom: 8px;
}
</style> 